package com.yd.sdk.adimp;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import com.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.OnUserEarnedRewardListener;
import com.google.android.gms.ads.RequestConfiguration;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.gms.ads.rewarded.RewardItem;
import com.google.android.gms.ads.rewarded.RewardedAd;
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback;
import com.unity3d.player.MyUnityPlayerActivity;
import com.yd.sdk.ad.AdAbstractClass;
import com.yd.sdk.ad.IAd;

import java.util.Arrays;

public class AdImp extends AdAbstractClass {

    private String AD_UNIT_ID_banner = "";
    private String AD_UNIT_ID_reward= "";
    private String AD_UNIT_ID_inter = "";

    private AdView _adView;
    private InterstitialAd _interstitial;
    private RewardedAd _rewarded;

    private boolean _isLoadingInterstitial = false;
    private boolean _isLoadingRewarded = false;
    private boolean _isShowBanner = false;

    private Handler handler;

    @Override
    public void onCreate(Activity activity,Bundle savedInstanceState) {
        this.activity = activity;

        handler = new Handler();

        // Initialize the Mobile Ads SDK.
        MobileAds.initialize(activity, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {}
        });

        // Set your test devices. Check your logcat output for the hashed device ID to
        // get test ads on a physical device. e.g.
        // "Use RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("ABCDEF012345"))
        // to get test ads on this device."
        MobileAds.setRequestConfiguration(
                new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList("A9F8210235BC361027486BE061BD9D93"))
                        .build());

        // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
        // values/strings.xml.

//        InitBanner();
//        InitInteristial();
//        InitReward();

    }

    private void InitBanner()
    {
        handler.post(new Runnable() {
            @Override
            public void run() {
                _adView = new AdView(activity);
                _adView.setAdUnitId(AD_UNIT_ID_banner);
                AdSize adSize = getAdSize();
                _adView.setAdSize(adSize);

                _adView.setAdListener(new AdListener() {
                    @Override
                    public void onAdClosed() {
                        super.onAdClosed();
                        OnAdClosed(IAd.AdType.Banner,"");
                    }

                    @Override
                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                        super.onAdFailedToLoad(loadAdError);
                        OnAdFailedToLoad(IAd.AdType.Banner,loadAdError.getCode() +"," + loadAdError.getMessage());
                    }

                    @Override
                    public void onAdOpened() {
                        super.onAdOpened();
                        OnAdOpened(IAd.AdType.Banner);
                    }

                    @Override
                    public void onAdLoaded() {
                        super.onAdLoaded();
                        OnAdSucessToLoad(IAd.AdType.Banner);
                    }

                    @Override
                    public void onAdClicked() {
                        super.onAdClicked();
                    }

                    @Override
                    public void onAdImpression() {
                        super.onAdImpression();
                    }
                });
            }
        });

    }

    private void InitInteristial()
    {

    }

    private void InitReward()
    {

    }

    @Override
    public void onPause() {
        if (_adView != null) {
            _adView.pause();
        }
    }

    @Override
    public void onResume() {
        if (_adView != null) {
            _adView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (_adView != null) {
            _adView.destroy();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantRes) {

    }

    @Override
    public void SetTestDeviceIds(String ids) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                String[] idsArray = ids.trim().split(",");
                MobileAds.setRequestConfiguration(
                        new RequestConfiguration.Builder().setTestDeviceIds(Arrays.asList(idsArray.clone()))
                                .build());

            }
        });



    }

    @Override
    public void SetAdIds(String bannerId, String interstitialId, String rewardId) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                AD_UNIT_ID_banner = bannerId;
                AD_UNIT_ID_inter = interstitialId;
                AD_UNIT_ID_reward = rewardId;
                Log.e("AdImp:" ,AD_UNIT_ID_banner+"," + AD_UNIT_ID_inter +","+ AD_UNIT_ID_reward);
                //如果给的横幅id不为空就初始化
                if(AD_UNIT_ID_banner != null && !"".equals(AD_UNIT_ID_banner))
                    InitBanner();
            }
        });

    }

    @Override
    public void LoadedAd(AdType adType) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                AdRequest adRequest = new AdRequest.Builder().build();
                switch (adType) {
                    case Banner:
                        _adView.loadAd(adRequest);
                        break;
                    case Interstitial:
                        if(_isLoadingInterstitial)return;
                        _isLoadingInterstitial = true;

                        InterstitialAd.load(activity, AD_UNIT_ID_inter, adRequest, new InterstitialAdLoadCallback() {
                            @Override
                            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                                super.onAdLoaded(interstitialAd);
                                _interstitial = interstitialAd;
                                interstitialAd.setFullScreenContentCallback(
                                        new FullScreenContentCallback() {
                                            @Override
                                            public void onAdDismissedFullScreenContent() {
                                                // Called when fullscreen content is dismissed.
                                                // Make sure to set your reference to null so you don't
                                                // show it a second time.
                                                _interstitial =  null;
                                                OnAdClosed(AdType.Interstitial,"");
                                            }

                                            @Override
                                            public void onAdFailedToShowFullScreenContent(AdError adError) {
                                                // Called when fullscreen content failed to show.
                                                // Make sure to set your reference to null so you don't
                                                // show it a second time.
                                                _interstitial =  null;
                                                OnAdClosed(AdType.Interstitial,"");
                                            }

                                            @Override
                                            public void onAdShowedFullScreenContent() {
                                                // Called when fullscreen content is shown.
                                                OnAdOpened(AdType.Interstitial);
                                            }
                                        });

                                _isLoadingInterstitial = false;
                                OnAdSucessToLoad(AdType.Interstitial);
                            }

                            @Override
                            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                                super.onAdFailedToLoad(loadAdError);
                                _isLoadingInterstitial = false;
                                OnAdFailedToLoad(AdType.Interstitial,loadAdError.getCode() +"," + loadAdError.getMessage());
                            }
                        });


                        break;
                    case Reward:
                        if(_isLoadingRewarded)return;
                        _isLoadingRewarded = true;

                        RewardedAd.load(
                                activity,
                                AD_UNIT_ID_reward,
                                adRequest,
                                new RewardedAdLoadCallback() {
                                    @Override
                                    public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {

                                        _rewarded = null;
                                        _isLoadingRewarded = false;
                                        OnAdFailedToLoad(AdType.Reward,loadAdError.getCode() +"," + loadAdError.getMessage());
                                    }

                                    @Override
                                    public void onAdLoaded(@NonNull RewardedAd rewardedAd) {
                                        _rewarded = rewardedAd;
                                        _isLoadingRewarded = false;

                                        rewardedAd.setFullScreenContentCallback(
                                                new FullScreenContentCallback() {
                                                    @Override
                                                    public void onAdShowedFullScreenContent() {
                                                        _rewarded =  null;
                                                        OnAdClosed(AdType.Reward,"");
                                                    }

                                                    @Override
                                                    public void onAdFailedToShowFullScreenContent(AdError adError) {
                                                        _rewarded =  null;
                                                        OnAdClosed(AdType.Reward,"");
                                                    }

                                                    @Override
                                                    public void onAdDismissedFullScreenContent() {
                                                        _rewarded =  null;
                                                        //_imp.OnAdClosed(AdType.Reward,true);
                                                        // Preload the next rewarded ad.
                                                        OnAdClosed(AdType.Reward,"");
                                                        //LoadedAd(AdType.Reward);
                                                    }
                                                });


                                        OnAdSucessToLoad(AdType.Reward);
                                    }
                                });

                        break;
                }
            }
        });



    }

    @Override
    public boolean IsAdAvailable(AdType adType) {
        boolean result = false;
        switch (adType)
        {
            case Banner:
                break;
            case Interstitial:
                result = _interstitial!=null;
                break;
            case Reward:
                result = _rewarded!=null;
                break;
        }
        return result;
    }

    @Override
    public void ShowBanner(BannerPos pos) {
//        MediationTestSuite.launch(this.activity);

        handler.post(new Runnable() {
            @Override
            public void run() {
                FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                lp.gravity = pos == BannerPos.Bottom? Gravity.BOTTOM : Gravity.TOP;
                if(_isShowBanner == false) {
                    ((MyUnityPlayerActivity) activity).GetUnityPlayer().addView(_adView, lp);
                    _isShowBanner = true;
                }
            }
        });



    }

    @Override
    public void ShowInterstitial() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (_interstitial != null) {
                    _interstitial.show(activity);
                }
            }
        });

    }

    @Override
    public void ShowReward() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(_rewarded != null)
                {
                    _rewarded.show(
                            activity,
                            new OnUserEarnedRewardListener() {
                                @Override
                                public void onUserEarnedReward(@NonNull RewardItem rewardItem) {
                                    // Handle the reward.
//                            Log.d("TAG", "The user earned the reward.");
                                    int rewardAmount = rewardItem.getAmount();
                                    String rewardType = rewardItem.getType();
                                    OnAdClosed(AdType.Reward,rewardAmount +","+rewardType);
                                }
                            });
                }
            }
        });
    }

    @Override
    public void HideAd(AdType adType) {

        handler.post(new Runnable() {
            @Override
            public void run() {
                switch (adType) {

                    case Banner:
                        if(_isShowBanner)
                        {
                            ((MyUnityPlayerActivity)activity).GetUnityPlayer().removeView(_adView);
                            _isShowBanner = false;
                        }
                        break;
                    case Interstitial:

                        break;
                    case Reward:
                        break;
                }
            }
        });
    }

    private AdSize getAdSize() {
        // Step 2 - Determine the screen width (less decorations) to use for the ad width.
        Display display = activity.getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float widthPixels = outMetrics.widthPixels;
        float density = outMetrics.density;

        int adWidth = (int) (widthPixels / density);

        // Step 3 - Get adaptive ad size and return for setting on the ad view.
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(activity, adWidth);
    }

}
